package com.xxxx;


import java.util.Properties;

import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.framework.quartz.QuartzJobManager;
import com.baomidou.framework.spring.DataLoadingInterceptor;
import com.baomidou.framework.spring.SpringContextHolder;
import com.baomidou.kisso.SSOAuthorization;
import com.baomidou.kisso.web.WebKissoConfigurer;
import com.baomidou.kisso.web.interceptor.SSOPermissionInterceptor;
import com.baomidou.kisso.web.interceptor.SSOSpringInterceptor;
import com.xxxx.common.MailContextHelper;
import com.xxxx.common.MailHelper;
import com.xxxx.util.mail.MailContextHelperImpl;



/**
 * @description: 配置类
 * @auchor: issuser
 * @date: 2016-08-31 14:37
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.xxxx")
@EnableCaching//标注启动缓存.
public class MyConfig extends WebMvcConfigurerAdapter{
	
	@Autowired 
    private ApplicationContext context; 
    
	
	@Bean(initMethod = "init", name = "beetlConfig")
    public BeetlGroupUtilConfiguration beetlConfig(){
        ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        ClasspathResourceLoader classpathResourceLoader = new ClasspathResourceLoader("templates/");
        beetlGroupUtilConfiguration.setResourceLoader(classpathResourceLoader);
        //读取配置文件信息
        beetlGroupUtilConfiguration.setConfigFileResource(patternResolver.getResource("classpath:beetl.properties"));
        return beetlGroupUtilConfiguration;
    }

    @Bean(name = "beetlViewResolver")
    public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration){
        BeetlSpringViewResolver bSVR = new BeetlSpringViewResolver();
        bSVR.setSuffix(".html");
        bSVR.setContentType("text/html;charset=UTF-8");
        bSVR.setOrder(0);
        bSVR.setConfig(beetlGroupUtilConfiguration);
        return bSVR;
    }
    

    @Bean(name="mailSender")
    public JavaMailSenderImpl mailSender(){
    	JavaMailSenderImpl jmsi = new JavaMailSenderImpl();
    	jmsi.setHost("smtp.sina.com");
    	jmsi.setPort(25);
    	jmsi.setProtocol("smtp");
    	jmsi.setUsername("hispringwind@sina.com");
    	jmsi.setPassword("1q2w3e");
    	Properties ps = new Properties();
    	ps.setProperty("mail.smtp.auth", "true");
    	ps.setProperty("mail.smtp.starttls.enable", "false");
    	ps.setProperty("mail.smtp.quitwait", "false");
    	jmsi.setJavaMailProperties(ps);
    	return jmsi;
    }
    @Bean(name="mailMail")
    public MailHelper getMailHelper(@Qualifier("mailSender") JavaMailSenderImpl mailSender){
    	MailHelper mh = new MailHelper();
    	MailContextHelper mailContextHelper =new MailContextHelperImpl(); 
    	mh.setMailContextHelper(mailContextHelper);
    	mh.setMailSender(mailSender);
    	mh.setMailTitle("SpringWind");
    	mh.setMailFrom("hispringwind@sina.com");
    	return mh;
    }
    
    
    @Bean(name = "quartzDataSource",initMethod="init", destroyMethod="close")
    public DruidDataSource getQuartzDataSource(){
    	DruidDataSource ds = new DruidDataSource();
    	ds.setDriverClassName("com.mysql.jdbc.Driver");
    	ds.setUrl("jdbc:mysql://localhost:3306/quartz_mysql_innodb?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull");
    	ds.setUsername("root");
    	ds.setPassword("root");
    	//配置初始化大小、最小、最大
    	ds.setInitialSize(3);
    	ds.setMinIdle(3);
    	ds.setMaxWait(60000);//配置获取连接等待超时的时间
    	ds.setTimeBetweenEvictionRunsMillis(60000);//配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
    	ds.setMinEvictableIdleTimeMillis(300000);//配置一个连接在池中最小生存的时间，单位是毫秒
		return ds; 
    }
    @Bean(name="schedulerFactory")
    public SchedulerFactoryBean getSchedulerFactory(@Qualifier("quartzDataSource") DruidDataSource ds){
    	ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
    	SchedulerFactoryBean sfb= new SchedulerFactoryBean();
    	// <!-- 应用上下文 -->
    	sfb.setApplicationContextSchedulerContextKey("applicationContext");
    	//<!-- ************** 两种配置数据源的方式根据实际情况进行选择 ************ -->
    	//<!-- 配置与应用同数据源 -->
    	sfb.setDataSource(ds);
    	//<!-- 配置根据配置文件配置数据源 -->
    	sfb.setConfigLocation(patternResolver.getResource("classpath:quartz.properties"));
    	// <!-- 这个是必须的，QuartzScheduler 延时启动，应用启动完后 QuartzScheduler 再启动 -->
    	sfb.setStartupDelay(30);//<!-- 这个是可选，QuartzScheduler启动时更新己存在的Job，这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 -->
    	sfb.setOverwriteExistingJobs(true);
    	sfb.setAutoStartup(true);
    	return sfb;
    }
    @Bean(name="quartzJobManager")
    public QuartzJobManager getQuartzJobManager(){
    	QuartzJobManager qjm =new QuartzJobManager();
    	return qjm;
    }
    
    /**
     * 配置拦截器
     */
    @Override
	public void addInterceptors(InterceptorRegistry registry) {
    	registry.addInterceptor(new SSOSpringInterceptor()).addPathPatterns("/**");
    	registry.addInterceptor(context.getBean(SSOPermissionInterceptor.class)).addPathPatterns("/**");
    	registry.addInterceptor(new DataLoadingInterceptor());
	}
    
    @Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    	registry.addResourceHandler("/error/**").addResourceLocations("classpath:/templates/error/");
    	registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/templates/favicon.ico");
	}
    
    /**
     * Spring 工具类 ，获取Spring容器中的上下文信息
     * @return
     */
    @Bean
    public SpringContextHolder getSpringContextHolder(){
    	return new SpringContextHolder();
    }
    
    //--------------Kisso start--------------------------
    @Bean(initMethod="initKisso")
    public WebKissoConfigurer kissoInit(){
    	WebKissoConfigurer webKissoConfigurer = new WebKissoConfigurer();
    	webKissoConfigurer.setSsoPropPath("sso.properties");
    	return webKissoConfigurer;
    }
    @Bean
    public SSOPermissionInterceptor getSSOPermissionInterceptor(SSOAuthorization authorization){
    	SSOPermissionInterceptor ssoPermissionInterceptor =new  SSOPermissionInterceptor();
    	ssoPermissionInterceptor.setIllegalUrl("/error/illegalAccess.html");
    	ssoPermissionInterceptor.setAuthorization(authorization);
    	return ssoPermissionInterceptor;
    }
    //--------------Kisso end--------------------------
    
    //--------------缓存开始start--------------------------
    /**
     * 据shared与否的设置,
     * Spring分别通过CacheManager.create()
     * 或new CacheManager()方式来创建一个ehcache基地.
     * 也说是说通过这个来设置cache的基地是这里的Spring独用,还是跟别的(如hibernate的Ehcache共享)
     * 
     */
    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
    	ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
    	EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
    	cacheManagerFactoryBean.setConfigLocation(patternResolver.getResource("classpath:ehcache.xml"));
    	cacheManagerFactoryBean.setShared(true);
    	return cacheManagerFactoryBean;
    }
    
    /**
     *  ehcache主要的管理器
     * @param bean
     * @return
     */
    @Bean
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
    	return new EhCacheCacheManager(bean.getObject());
    }
    //--------------缓存开始end--------------------------
    
   
    
}
